"use client";

import React, { useState, useEffect, useCallback } from "react";
import axios from "axios";
import { 
  CheckCircle, 
  XCircle 
} from "lucide-react";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "./ui/dialog";

// 预定义的模型列表
const PREDEFINED_MODELS = [
  { id: "llama3", name: "Llama 3" },
  { id: "llama3:8b", name: "Llama 3 (8B)" },
  { id: "llama3:70b", name: "Llama 3 (70B)" },
  { id: "deepseek-r1:7b", name: "deepseek-r1:7b" },
  { id: "deepseek-r1:1.5b", name: "deepseek-r1:1.5b" },
  { id: "phi3", name: "Phi-3" },
  { id: "phi3:mini", name: "Phi-3 Mini" },
  { id: "phi3:small", name: "Phi-3 Small" },
  { id: "phi3:medium", name: "Phi-3 Medium" },
  { id: "mistral", name: "Mistral" },
  { id: "mistral:7b", name: "Mistral (7B)" },
  { id: "mixtral", name: "Mixtral" },
  { id: "mixtral:8x7b", name: "Mixtral (8x7B)" },
  { id: "gemma", name: "Gemma" },
  { id: "gemma:7b", name: "Gemma (7B)" },
  { id: "gemma:2b", name: "Gemma (2B)" },
];

export interface Settings {
  apiEndpoint: string;
  apiKey: string;
  modelId: string;
  temperature: number;
  top_p: number;
  top_k: number;
  repeat_penalty: number;
  stop_words: string;
  streaming: boolean;
}

interface ModelInfo {
  models: Array<{
    name: string;
    size: number;
  }>;
}

interface SettingsDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

export function SettingsDialog({ open, onOpenChange }: SettingsDialogProps) {
  const [localSettings, setLocalSettings] = useState<Settings>({
    apiEndpoint: "",
    apiKey: "",
    modelId: "deepseek-r1:7b",
    temperature: 0.7,
    top_p: 0.9,
    top_k: 40,
    repeat_penalty: 1.1,
    stop_words: "",
    streaming: true,
  });

  const [isSaving, setIsSaving] = useState(false);
  const [saveStatus, setSaveStatus] = useState<{
    success: boolean | null;
    message: string;
  }>({
    success: null,
    message: "",
  });

  useEffect(() => {
    const fetchSettings = async () => {
      try {
        const response = await axios.get('/api/settings');
        const settings = response.data;
        console.log("Settings loaded from server:", settings);
        
        // 合并服务器设置和本地存储设置
        if (typeof window !== 'undefined') {
          const savedApiKey = localStorage.getItem("apiKey") || settings.apiKey || "";
          const savedApiEndpoint = localStorage.getItem("apiEndpoint") || settings.apiEndpoint || "";
          const savedModelId = localStorage.getItem("modelId") || settings.model || "deepseek-r1:7b";
          
          setLocalSettings(prev => ({
            ...prev,
            apiEndpoint: savedApiEndpoint,
            apiKey: savedApiKey,
            modelId: savedModelId,
            temperature: settings.temperature || prev.temperature,
            top_p: settings.topP || prev.top_p,
            streaming: settings.streamingEnabled || prev.streaming,
          }));
    }
      } catch (error) {
        console.error("Error fetching settings:", error);
        
        // 错误时回退到仅使用本地存储
        if (typeof window !== 'undefined') {
          const savedApiKey = localStorage.getItem("apiKey") || "";
          const savedApiEndpoint = localStorage.getItem("apiEndpoint") || "";
          const savedModelId = localStorage.getItem("modelId") || "deepseek-r1:7b";
          
          setLocalSettings(prev => ({
            ...prev,
            apiEndpoint: savedApiEndpoint,
            apiKey: savedApiKey,
            modelId: savedModelId,
          }));
        }
      }
    };
    
    fetchSettings();
  }, []);

  useEffect(() => {
    if (open) {
      // 当对话框打开时重新获取设置
  const fetchSettings = async () => {
    try {
          const response = await axios.get('/api/settings');
          const settings = response.data;
          
          // 合并服务器设置和本地存储设置
          if (typeof window !== 'undefined') {
            const savedApiKey = localStorage.getItem("apiKey") || settings.apiKey || "";
            const savedApiEndpoint = localStorage.getItem("apiEndpoint") || settings.apiEndpoint || "";
            const savedModelId = localStorage.getItem("modelId") || settings.model || "deepseek-r1:7b";
            
            setLocalSettings(prev => ({
              ...prev,
              apiEndpoint: savedApiEndpoint,
              apiKey: savedApiKey,
              modelId: savedModelId,
              temperature: settings.temperature || prev.temperature,
              top_p: settings.topP || prev.top_p,
              streaming: settings.streamingEnabled || prev.streaming,
            }));
          }
    } catch (error) {
      console.error("Error fetching settings:", error);
    }
  };
      
      fetchSettings();
    }
  }, [open]);

  const testApiConnection = useCallback(async () => {
    if (!localSettings.apiEndpoint) {
      return;
    }

    try {
      const response = await axios.get('/api/settings');
      console.log("API connection test successful:", response.data);
      setSaveStatus({
        success: true,
        message: "连接测试成功！",
      });
    } catch (error) {
      console.error("API connection test failed:", error instanceof Error ? error.message : String(error));
      setSaveStatus({
        success: false,
        message: "连接测试失败！",
      });
    }
  }, [localSettings.apiEndpoint]);

  const handleSaveSettings = async () => {
    setIsSaving(true);
    setSaveStatus({ success: null, message: "" });

    try {
      // 检查是否是本地 API 地址
      const isLocalApi = localSettings.apiEndpoint.includes('localhost') || 
                          localSettings.apiEndpoint.includes('127.0.0.1');

      // 如果是本地 API 且未提供密钥，则不要求密钥
      const isValidSettings = localSettings.apiEndpoint.trim() && 
                             (isLocalApi || localSettings.apiKey.trim());

      if (!isValidSettings) {
        setSaveStatus({
          success: false,
          message: "请提供有效的 API 设置。本地模型只需要 API 地址，远程模型需要 API 地址和密钥。",
        });
        setIsSaving(false);
        return;
      }

      if (typeof window !== 'undefined') {
        localStorage.setItem("apiEndpoint", localSettings.apiEndpoint);
        localStorage.setItem("apiKey", localSettings.apiKey);
        localStorage.setItem("isLocalApi", String(isLocalApi));
        localStorage.setItem("modelId", localSettings.modelId);
      }
      
      await axios.post("/api/settings", {
        ...localSettings,
        model: localSettings.modelId, // 后端使用 model 字段
      });
      
      setSaveStatus({
        success: true,
        message: "设置已保存！",
      });
      
      await testApiConnection();
      
      setTimeout(() => {
        onOpenChange(false);
      }, 1500);
    } catch (error) {
      console.error("Error saving settings:", error instanceof Error ? error.message : String(error));
      setSaveStatus({
        success: false,
        message: "保存设置时出错！",
      });
    } finally {
      setIsSaving(false);
    }
  };

  const handleInputChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>
  ) => {
    const { name, value } = e.target;
    setLocalSettings((prev) => ({
      ...prev,
      [name]: value,
    }));
  };

  // 检查是否是本地 API
  const isLocalApi = localSettings.apiEndpoint.includes('localhost') || 
                     localSettings.apiEndpoint.includes('127.0.0.1');

  if (!open) return null;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>API 设置</DialogTitle>
        </DialogHeader>
              <div className="space-y-4">
                <div>
            <label htmlFor="apiEndpoint" className="block text-sm font-medium mb-1">
              API 服务器地址
            </label>
                  <Input
                    id="apiEndpoint"
                    name="apiEndpoint"
              type="text"
                    value={localSettings.apiEndpoint}
                    onChange={handleInputChange}
              placeholder="例如: http://localhost:11434/api/chat"
              className="mb-4"
                  />
            <p className="text-xs text-slate-500 mt-1">
              本地模型 API 地址通常为 http://localhost:11434/api/chat 或 http://localhost:11434/api/generate
                  </p>
                </div>

                <div>
            <label htmlFor="apiKey" className="block text-sm font-medium mb-1 flex items-center justify-between">
              <span>API 密钥</span>
              {isLocalApi && <span className="text-xs text-green-500">本地模型可选</span>}
            </label>
                  <Input
              id="apiKey"
              name="apiKey"
              type="password"
              value={localSettings.apiKey}
                    onChange={handleInputChange}
              placeholder={isLocalApi ? "本地模型可不填写密钥" : "输入您的 API 密钥"}
              className="mb-4"
                  />
            <p className="text-xs text-slate-500 mt-1">
              您的 API 密钥仅存储在您的浏览器中，不会发送到我们的服务器
                  </p>
                </div>

          {isLocalApi && (
                <div>
              <label htmlFor="modelId" className="block text-sm font-medium mb-1">
                模型
              </label>
              <select
                id="modelId"
                name="modelId"
                value={localSettings.modelId}
                    onChange={handleInputChange}
                className="w-full px-3 py-2 border border-slate-300 rounded-md text-sm shadow-sm focus:outline-none focus:border-blue-500 dark:bg-slate-800 dark:border-slate-700 dark:text-slate-300"
              >
                {PREDEFINED_MODELS.map(model => (
                  <option key={model.id} value={model.id}>
                    {model.name}
                  </option>
                ))}
              </select>
              <p className="text-xs text-slate-500 mt-1">
                选择您在 Ollama 中已安装的模型
                  </p>
                </div>
          )}
                  
          <div className="flex justify-end space-x-2">
                    <Button
              variant="secondary" 
              onClick={() => onOpenChange(false)}
            >
              取消
                    </Button>
                      <Button
              onClick={handleSaveSettings} 
              disabled={isSaving || !localSettings.apiEndpoint || (!isLocalApi && !localSettings.apiKey)}
                      >
              {isSaving ? "保存中..." : "保存设置"}
                      </Button>
        </div>

          {saveStatus.success !== null && (
            <div className={`mt-2 text-sm ${
                saveStatus.success
                  ? "text-green-600 dark:text-green-400"
                  : "text-red-600 dark:text-red-400"
            }`}>
              {saveStatus.success ? (
                <CheckCircle className="h-4 w-4 inline-block mr-1.5" />
              ) : (
                <XCircle className="h-4 w-4 inline-block mr-1.5" />
              )}
              {saveStatus.message}
            </div>
          )}
        </div>
      </DialogContent>
    </Dialog>
  );
} 